// shop.js
const app = getApp();

// 基础升级费用
const BASE_UPGRADE_COST = {
  egg: 50,
  bread: 80,
  coffee: 60
};

// 最大等级
const MAX_LEVEL = 10;

Page({
  data: {
    userData: {
      coins: 0,
      level: 1,
      equipmentLevels: {
        egg: 1,
        bread: 1,
        coffee: 1
      }
    },
    showUpgradeSuccess: false
  },

  onLoad: function() {
    // 从全局获取用户数据
    if (app.globalData.userData) {
      this.setData({
        'userData': app.globalData.userData
      });
    }
  },

  onShow: function() {
    // 每次显示页面时刷新用户数据
    if (app.globalData.userData) {
      this.setData({
        'userData': app.globalData.userData
      });
    }
  },

  // 计算升级费用
  getUpgradeCost: function(equipmentType) {
    const currentLevel = this.data.userData.equipmentLevels[equipmentType];
    
    // 如果已经达到最大等级，显示"已满级"
    if (currentLevel >= MAX_LEVEL) {
      return "已满级";
    }
    
    // 升级费用随等级增加而增加
    return BASE_UPGRADE_COST[equipmentType] * Math.pow(1.5, currentLevel - 1);
  },

  // 判断是否可以升级
  canUpgrade: function(equipmentType) {
    const currentLevel = this.data.userData.equipmentLevels[equipmentType];
    
    // 如果已经达到最大等级，不能再升级
    if (currentLevel >= MAX_LEVEL) {
      return false;
    }
    
    // 计算升级费用
    const cost = this.getUpgradeCost(equipmentType);
    
    // 判断金币是否足够
    return this.data.userData.coins >= cost;
  },

  // 升级设备
  upgradeEquipment: function(e) {
    const equipmentType = e.currentTarget.dataset.type;
    
    // 判断是否可以升级
    if (!this.canUpgrade(equipmentType)) {
      return;
    }
    
    // 计算升级费用
    const cost = this.getUpgradeCost(equipmentType);
    
    // 更新用户数据
    const userData = this.data.userData;
    userData.coins -= cost;
    userData.equipmentLevels[equipmentType] += 1;
    
    // 更新数据
    this.setData({
      userData,
      showUpgradeSuccess: true
    });
    
    // 保存用户数据
    app.updateUserData(userData);
    
    // 添加升级成功的动画效果
    wx.vibrateShort({
      type: 'medium'
    });
    
    // 一段时间后隐藏升级成功提示
    setTimeout(() => {
      this.setData({
        showUpgradeSuccess: false
      });
    }, 1500);
  },

  // 在模板中使用的辅助函数
  getUpgradeCost: function(equipmentType) {
    const currentLevel = this.data.userData.equipmentLevels[equipmentType];
    
    // 如果已经达到最大等级，显示"已满级"
    if (currentLevel >= MAX_LEVEL) {
      return "已满级";
    }
    
    // 升级费用随等级增加而增加
    return Math.floor(BASE_UPGRADE_COST[equipmentType] * Math.pow(1.5, currentLevel - 1));
  },

  canUpgrade: function(equipmentType) {
    const currentLevel = this.data.userData.equipmentLevels[equipmentType];
    
    // 如果已经达到最大等级，不能再升级
    if (currentLevel >= MAX_LEVEL) {
      return false;
    }
    
    // 计算升级费用
    const cost = this.getUpgradeCost(equipmentType);
    
    // 判断金币是否足够
    return this.data.userData.coins >= cost;
  }
});